#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 1e4 + 5;
const int M = 2e4 + 5;

int n, m, k;
int head[N];
int ver[M << 1], W[M << 1], Next[M << 1], tot;
int dis[N][105];

void add(int u, int v, int w) {
  ++tot;
  ver[tot] = v;
  W[tot] = w;
  Next[tot] = head[u];
  head[u] = tot;
}

struct Node {
  int u, d;
  bool operator<(const Node& o) const { return d > o.d; }
};
void dijkstra() {
  memset(dis, 0x3f, sizeof(dis));
  priority_queue<Node> pq;
  dis[1][0] = 0;
  pq.push(Node{1, 0});
  while (pq.size()) {
    Node now = pq.top();
    pq.pop();
    int u = now.u, d = now.d;
    if (dis[u][d % k] < d) continue;
    for (int i = head[now.u]; i; i = Next[i]) {
      int v = ver[i];
      int w = W[i];
      int d2 = d + 1;
      if (d < w) d2 += (w - d + k - 1) / k * k;
      int s = d2 % k;
      if (dis[v][s] > d2) {
        dis[v][s] = d2;
        pq.push(Node{v, d2});
      }
    }
  }
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n >> m >> k;
  rep(i, 1, m) {
    int u, v, w;
    cin >> u >> v >> w;
    add(u, v, w);
  }
  dijkstra();
  if (dis[n][0] == 0x3f3f3f3f)
    cout << -1;
  else
    cout << dis[n][0];
  return 0;
}